<template>
  <div class="energy-data-container">
    <CPageTable @register="registerPage" v-model:searchForm="searchForm">
      <template #headerRightButton>
        <el-button @click="handleExport()" type="primary">
          <CIcon type="c-xian-daochu" class="g-mr4"></CIcon>
          导出为excel
        </el-button>
      </template>
    </CPageTable>
  </div>
</template>
<script lang="ts">
export default {
  name: 'ActiveDataDetail'
};
</script>
<script lang="ts" setup>
import { reactive } from 'vue';
import { useDetail } from './useDetail';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { useExport } from '@/hooks/useExport';
import { useMessage } from '@/hooks/useMessage';
import { exportActiveData } from '@/apis/eci/dataManagement/detail';
import type { GetListFillTaskResult } from '@/apis/eci/dataManagement/model/detailModel';
import { cloneDeep } from 'lodash';

const { searchForm, tableOptions, searchOptions, handleParams, tableFieldsSetting } =
  useDetail(onSearchFormCodeChange);
const { createMessage } = useMessage();
const { handleExportFile } = useExport();
const options = reactive<CPageTableProps>({
  title: '活动数据明细',
  searchOptions,
  tableOptions,
  tableFieldsSetting,
  enableFieldsSetting: true
});
const [registerPage, { refresh, getTotal, setProps }] = useCPageTable(options);

const handleExport = () => {
  if (getTotal() > 0) {
    const params = handleParams();
    handleExportFile(exportActiveData, params);
  } else {
    createMessage.warning('没有可以导出的数据！');
  }
};

function onSearchFormCodeChange(list: GetListFillTaskResult[]) {
  console.log('onSearchFormCodeChange', searchForm.organizationCode, list);
  const op = cloneDeep(searchOptions);
  op[1].disabled = false;
  // 获取已选中组织的盘查周期列表
  const selectOrg = list.find(n => n.organizationCode === searchForm.organizationCode);
  if (selectOrg) searchForm.organizationName = selectOrg.organizationName;
  const periodsList = selectOrg?.periods || [];
  console.log('onSearchFormCodeChange periodsList', periodsList);
  op[1].options = periodsList.map(item => {
    return {
      label: item,
      value: item
    };
  });
  // 如果有盘查周期，设置
  if (op[1].options?.length) {
    searchForm.inventoryYear = op[1].options[0].value;
  } else {
    searchForm.inventoryYear = '';
  }
  console.log('onSearchFormChange', op, searchForm.inventoryYear);
  setProps({
    searchOptions: op
  });
  refresh();
}
</script>

<style lang="scss" scoped>
:deep(.merged-cell) {
  position: relative;
}
:deep(.merged-cell > .vxe-cell) {
  position: absolute;
  top: 11px;
}
</style>
